import time
import traceback

import serial
from log import logger

print = logger.info
class HoneyPrintClient:

    def __init__(self):
        self.ser = None
        # self.ser = serial.Serial("COM4", 115200)
        # if self.ser.isOpen():  # 判断串口是否成功打开
        #     print("打开串口成功。")
        #     print(self.ser.name)  # 输出串口号
        # else:
        #     print("打开串口失败。")

        # pof缓存
        self.pre_template_str = ''
        self.pre_template_path = ''
    def open(self):
        try:
            self.ser = serial.Serial("COM4", 115200)
            if self.ser.isOpen():  # 判断串口是否成功打开
                print("打开串口成功")
                print(self.ser.name)  # 输出串口号
            else:
                print("打开串口失败。")
            return True
        except:
            logger.error(traceback.format_exc())
            return False
    def printOneLabel(self, res_labelContent_list=[], template_path=r'C:\zxc\other\50175378-001_D.POF'):
        '''

        :param res_labelContent: [{}, {}]
        :param template_path: \\ch3uw1050\THLabel\Barone\POF\~
        :return:
        '''
        try:
            is_ok = True
            print('print label...')
            # 读取template
            if template_path == self.pre_template_path:
                template_str = self.pre_template_str
            else:
                try:
                    with open(template_path) as f:
                        template_str = f.read()
                except:
                    logger.info(traceback.format_exc())
                    logger.error(f'读取打印模板 {template_path}失败 ')
                    is_ok = False
                    self.close()
                    self.open()
                    return is_ok
                self.pre_template_path = template_path
                self.pre_template_str = template_str # 避免重复读取

            for row_dict in res_labelContent_list:
                # F_VariableName F_VariableValue
                #F_VariableName
                old_str = f"/*PROMPT:{row_dict['F_VariableName']}@1@*/"
                new_str = row_dict['F_VariableValue']
                isFind = template_str.find(old_str) # -1 not find other index
                print(f'{old_str} to {new_str}  {isFind}')
                if isFind != -1:
                    template_str = template_str.replace(old_str, new_str)

            # print(template_str)
            # template_str = template_str[::-1]
            res = self.ser.write(template_str.encode('utf-8'))
            # time.sleep(10)
            print(f'feedback {self.ser.read(self.ser.in_waiting)}')
            print(f'len of print_data {res}')
            return is_ok
            # # 读取响应
            # response = self.ser.readline()  # 读一行
            # if response:
            #     print("接收到:", response.decode('utf-8'))
            # else:
            #     print("未收到响应")
        except Exception as e:
            # logger.error(e)
            logger.error(traceback.format_exc())
            is_ok = False
            self.close()
            self.open()
            return is_ok

    def close(self):
        self.ser.close()
        print('close series')

class SimHoneyPrintClient:

    def __init__(self):
        pass

    def open(self):
        pass
        return True


    def printOneLabel(self, res_labelContent_list=[], template_path=r'C:\zxc\other\50175378-001_D.POF'):
        '''

        :param res_labelContent: [{}, {}]
        :param template_path: \\ch3uw1050\THLabel\Barone\POF\~
        :return:
        '''
        pass

    def close(self):
        pass

def test_honeyPrintClient():
    print_handle = HoneyPrintClient()

    # res_labelContent_list = [
    #     {'F_MDCSDeviceName': None, 'F_MDCSVariable': True, 'F_MDCSVariableName': 'WIFI',
    #     'F_VariableName': 'MAC','F_VariableValue': '1234'},
    #     {'F_MDCSDeviceName': None, 'F_MDCSVariable': True, 'F_MDCSVariableName': 'IMEI',
    #     'F_VariableName': '1_IMEI', 'F_VariableValue': '1234'},
    #     {'F_MDCSDeviceName': None, 'F_MDCSVariable': True, 'F_MDCSVariableName': 'ESIMID',
    #     'F_VariableName': 'ESIM_ID','F_VariableValue': '1234'},
    #     {'F_MDCSDeviceName': None, 'F_MDCSVariable': False, 'F_MDCSVariableName': '',
    #     'F_VariableName': 'BOMREV', 'F_VariableValue': '1234'},
    #     {'F_MDCSDeviceName': None, 'F_MDCSVariable': False, 'F_MDCSVariableName': '',
    #     'F_VariableName': 'MR', 'F_VariableValue': '412.01.08.0084-G'},
    #     {'F_MDCSDeviceName': None, 'F_MDCSVariable': True, 'F_MDCSVariableName': 'IMEI2',
    #     'F_VariableName': '2_IMEI','F_VariableValue': '1234'}
    # ]
    res_labelContent_list = []

    # template_path = r'C:\zxc\code\shwj_honey\printer\pof\3010-0247-002_F.POF'
    template_path = r'C:\zxc\code\shwj_honey\printer\pof\50176073-002_H.POF'
    print_handle.printOneLabel(res_labelContent_list, template_path)
    print_handle.close()



def test_mess_printer():

    part_number = 'CT45-L1N-28D120G'
    serial_number = '23059B2B78'


    from sql_server.HuoniMessClient import HuoniMessClient
    mess_handle = HuoniMessClient()
    # printer handle
    printer_handle = HoneyPrintClient()

    rows = mess_handle.getBzBySku(sku = part_number)
    res_pd = rows[0]
    # 2 get Label Name and label content from mess, then print
    # print(f'{thread_name} 2 get Label Name and label content')  # need pn, sn
    res_labelNames = mess_handle.getLabelName(F_Unit_type=res_pd['F_Unit_type'],
                                              F_LabelGroupName='KitLabel')  # [{},{}] ones
    print(res_labelNames)
    # F_LabelName = res_labelNames[0]['F_LabelName'] #
    for res in res_labelNames:  # maybe muti labels, now ones
        # get label content
        F_LabelName = res['F_LabelName']
        res_labelContents = mess_handle.getLabelContent(F_LabelName=F_LabelName,
                                                        F_Unit_type=res_pd['F_Unit_type'])  # [{},{}]
        print(res_labelContents)
        # get print value from qcdcs
        res_labelvars = mess_handle.getLabelVarFromQCDCS(pn=part_number, sn=serial_number)
        # print(f'{thread_name} res_labelvars {res_labelvars}')  # bda, imei, imei2, meid, meid2, wifi
        for res_labelContent in res_labelContents:
            if res_labelContent['F_MDCSVariable']:  # is get value from cdcs
                # value = 'getFromCdcs' # # get from cdcs todo
                b = res_labelContent['F_MDCSVariableName']
                for res_labelvar in res_labelvars:  # loop twice
                    a = res_labelvar['Type']
                    if a == b:
                        print(f"{res_labelvar['Type']}  {res_labelvar['Value']}")
                        # value = res_labelvar['Value']
                        res_labelContent['F_VariableValue'] = res_labelvar['Value']
                        break
        res_labelContents.append({'F_VariableName': 'ITEM', 'F_VariableValue': part_number})
        res_labelContents.append({'F_VariableName': 'DSN', 'F_VariableValue': serial_number})

        # control printer to print label
        pof_path = f'./pof/{F_LabelName}'  # \\ch3uw1050\THLabel\Barone\POF\
        pof_path = fr'\\ch3uw1050\THLabel\Barone\POF\{F_LabelName}'
        printer_handle.printOneLabel(res_labelContents, template_path=pof_path)


if __name__ == "__main__":
    # test_honeyPrintClient()
    test_mess_printer()